<template>
 <el-dialog
  :title="dataForm.id===0 ? '新增' : '修改'"
  :close-on-click-modal = "false"
  :visible.sync = "visible">
<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native = "dataFormSubmit()" label-width="100px">
    <!-- 下拉选择框提示编号 --><!-- 还没修改 选择器（自定义模版）  OK-->
    <el-form-item label="设备名称" prop="deviceId">
        <el-select v-model="dataForm.deviceId" filterable clearable placeholder="设备名称" :disabled="dataForm.id">
            <el-option
            v-for="item in dataForm.deviceList"
            :key="item.deviceId"
            :label="item.deviceName"
            :value="item.deviceId">
            <span style="float: left">{{ item.deviceName }}</span> 
            <span style="float: right ; color: #8492a6; font-size: 10px">{{ item.deviceId }}</span>
        </el-option>
    </el-select>
</el-form-item>
<!-- 单选 -->
<el-form-item label="保养计划: " prop="maintenancePlan">
    <el-radio-group v-model="dataForm.maintenancePlan" @change="changeMaintenancePlan">
        <el-radio  label = "1" border >方案一</el-radio>
        <el-radio  label = "2" border >方案二</el-radio>
    </el-radio-group>
</el-form-item>

<template v-if="dataForm.maintenancePlan === '1'" >
<el-row :gutter="25">
    <el-col :span="11">
        <el-form-item label="保养周期（天）" prop="maintenanceCycle">
            <el-input v-model.number="dataForm.maintenanceCycle" placeholder="保养周期" clearable></el-input>
        </el-form-item>
        <el-form-item label="保养计划详情: ">
            <el-button type="text" @click="open1">点击打开查询方案一详情</el-button>
        </el-form-item>
    </el-col>
  <el-col :span="11">
    <el-form-item label="提前提醒（天）" prop="advanceTime" >
            <el-input v-model.number="dataForm.advanceTime" placeholder="提前预警时间" clearable></el-input>
        </el-form-item>
        
    </el-col>
</el-row>
</template>

<template v-if="dataForm.maintenancePlan === '2'">
      <el-form-item label="使用时长（小时）" prop="maintenanceCycle">
        <el-input v-model.number="dataForm.maintenanceCycle" placeholder="请输入使用时长" clearable></el-input>
      </el-form-item>
      <el-form-item label="保养计划详情: ">
        <el-button type="text" @click="open2">点击打开查询方案二详情</el-button>
    </el-form-item>
</template>

<!-- <el-select :disabled="someValue === 'true'"></el-select> -->

</el-form>
<span slot="footer" class="dialog-footer">
    <el-button @click="visible = false">取消</el-button>
    <el-button type="primary" @click="dataFormSubmit(),sendDataToBackend()">确定</el-button>
</span>
</el-dialog>

</template>

<script>
import { method } from 'lodash';
import { valid } from 'semver';
// import axios from 'axios';

export default{
    data(){
        // 自定义校验规则：确保 maintenanceCycle > advanceTime
        const validateXAndY = (rule, value, callback) => {
            const { maintenancePlan, maintenanceCycle, advanceTime } = this.dataForm;
            if (maintenancePlan === '1') {
                // 方案一：maintenanceCycle > advanceTime
                if (maintenanceCycle <= advanceTime) {
                    callback(new Error('保养周期必须大于提前日期'));
                } else {
                    callback();
                }
            } else if (maintenancePlan === '2') {
                // 方案二：maintenanceCycle = advanceTime
                if (maintenanceCycle <= 0) {
                    callback(new Error('使用时长必须大于0'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };

        return{
            visible:false,
            dataForm:{
                id: 0,
                maintenancePlan:'',
                deviceId:'',
                createTime:'',
                createBy:'',
                updateTime:'',
                updateBy:'',
                deviceList:[],
                maintenanceCycle:'',
                advanceTime:'',

            },
            dataRule:{
                deviceId:[
                    { required: true, message: '设备编号不能为空', trigger: 'blur'}
                ],
                maintenancePlan:[
                    { required: true, message: '请选择保养方式', trigger: 'blur'},
                ],
                maintenanceCycle:[
                    { required: true, message: '请输入值', trigger: 'blur' },
                    { type:'number', message: '必须为数字', trigger: ['blur', 'change']},
                    { validator: validateXAndY, trigger: 'blur' },
                ],
                advanceTime:[
                    { required: true, message: '请输入值', trigger: 'blur' },
                    { type:'number', message: '必须为数字', trigger: ['blur', 'change']},
                    { validator: validateXAndY, trigger: 'blur' },
                ]
            },
            
        }
    },
    methods:{
        changeMaintenancePlan(plan) {
            this.dataForm.maintenancePlan = plan;
            // 重置相关字段
            this.dataForm.maintenanceCycle = '';
            this.dataForm.advanceTime = '';
        },
        open1(){
            const message =`每<strong> ${this.dataForm.maintenanceCycle}天</strong>保养一次，到期前<strong> ${this.dataForm.advanceTime}天</strong>提醒`
            this.$alert(message, '方案一', {
                confirmButtonText:'知道了',
                dangerouslyUseHTMLString: true
            })
        },
        open2(){
            this.$alert(`亮灯总时长到达<strong> ${this.dataForm.maintenanceCycle}小时</strong>提醒保养`, '方案二', {
                confirmButtonText:'知道了',
                dangerouslyUseHTMLString: true
            })
        },
        init(id){
            this.dataForm.id = id || 0
            // console.log(this.dataForm.id);
            this.$http({
                url:this.$http.adornUrl('/dss/maintenanceWarning/deviceList'),
                method:'get',
                params:this.$http.adornParams()
            }).then(({data}) => {
                if(data && data.code === 0){
                    this.dataForm.deviceList = data.deviceList
                }
            }).then(() => {
                this.visible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields()
                    
                })
            }).then(()=> {
                console.log(this.dataForm.id)
                if(this.dataForm.id){
                    this.$http({
                        url:this.$http.adornUrl(`/dss/maintenanceWarning/info/${this.dataForm.id}`),
                        method:'get',
                        params:this.$http.adornParams()
                    }).then(({data}) => {
                        if(data && data.code === 0){
                        console.log(data.maintenanceWarning.id)
                            this.dataForm.id = data.maintenanceWarning.id 
                            this.dataForm.deviceId = data.maintenanceWarning.deviceId
                            this.dataForm.maintenancePlan = data.maintenanceWarning.maintenancePlan
                            this.dataForm.maintenanceCycle = data.maintenanceWarning.maintenanceCycle
                            this.dataForm.advanceTime = data.maintenanceWarning.advanceTime
                            // this.dataForm.id = data.deviceInformationEntity.id 
                            // this.dataForm.deviceId = data.deviceInformationEntity.deviceId
                            // this.dataForm.maintenancePlan = data.deviceInformationEntity.maintenancePlan

                        }
                    })
                }

            })
            
        },
        //表单提交
        dataFormSubmit(){
            // console.log(this.dataForm.Y);
            this.$refs['dataForm'].validate((valid) => {
                if(valid){
                    this.$http({
                        url:this.$http.adornUrl(`/dss/maintenanceWarning/${!this.dataForm.id ? 'save' : 'update'}`),
                        method:'post',
                        data:this.$http.adornData({
                            'id':this.dataForm.id || undefined,
                            'deviceId':this.dataForm.deviceId,
                            'maintenancePlan':this.dataForm.maintenancePlan,
                            'createTime':this.dataForm.createTime,
                            'createBy':this.dataForm.createBy,
                            'updateTime':this.dataForm.updateTime,
                            'updateBy':this.dataForm.updateBy,
                            'maintenanceCycle':this.dataForm.maintenanceCycle,
                            'advanceTime': this.dataForm.advanceTime,
                            
                        })
                    }).then(({data}) => {
                        if (data && data.code === 0) {
                            this.$message({   
                                message: '操作成功', 
                                type: 'success',  
                                duration: 1500,  
                                onClose: () => {
                                    this.visible = false
                                    this.$emit('refreshDataList')
                                }
                            })
                        }else{
                            this.$message.error(data.msg)
                        }
                    })
                }
            }) 
        },
    }
}
</script>